package com.yc.cloud.admin.utils;

import cn.hutool.core.util.StrUtil;
import com.yc.cloud.admin.config.MediaKitProperties;
import com.yc.cloud.entity.HwCamera;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;

/**
 * 流地址构建工具类
 * 
 * @author kinggu
 * @since 2025-10-10
 */
@Slf4j
@Component
public class StreamUrlBuilder {
    
    @Resource
    private MediaKitProperties mediaKitProperties;
    
    private static MediaKitProperties staticMediaKitProperties;
    
    @PostConstruct
    public void init() {
        staticMediaKitProperties = mediaKitProperties;
    }
    
    /**
     * 根据摄像头信息生成 RTSP 流地址
     * 
     * @param camera 摄像头对象
     * @return RTSP 流地址，如果配置不完整返回 null
     */
    public static String buildRtspUrl(HwCamera camera) {
        if (camera == null) {
            return null;
        }
        
        if (StrUtil.isAllNotBlank(camera.getCameraUsername(), camera.getCameraPassword(), camera.getCameraIp())
                && camera.getCameraPort() != null) {
            return String.format("rtsp://%s:%s@%s:%d/h264/ch1/main/av_stream",
                    camera.getCameraUsername(),
                    camera.getCameraPassword(),
                    camera.getCameraIp(),
                    camera.getCameraPort());
        }
        return null;
    }
    
    /**
     * 根据摄像头信息生成 RTMP 推流地址
     * 格式：rtmp://host:{rtmpPort}/{app}/sipUsername_videoChannel
     * 从配置文件中动态获取 rtmpPort 和 app
     * 
     * @param camera 摄像头对象
     * @return RTMP 流地址，如果配置不完整返回 null
     */
    public static String buildRtmpUrl(HwCamera camera) {
        if (camera == null) {
            return null;
        }
        
        if (StrUtil.isAllNotBlank(camera.getSipUsername(), camera.getVideoChannel())) {
            // 构建流名称：sipUsername_videoChannel
            String streamId = camera.getSipUsername() + "_" + camera.getVideoChannel();
            
            // 从配置中获取 MediaKit 服务器地址、RTMP 端口和应用名
            String host = "127.0.0.1"; // 默认值
            Integer rtmpPort = 1935; // 默认值
            String app = "rtp"; // 默认值
            
            if (staticMediaKitProperties != null) {
                if (StrUtil.isNotBlank(staticMediaKitProperties.getHost())) {
                    host = staticMediaKitProperties.getHost();
                }
                if (staticMediaKitProperties.getRtmpPort() != null) {
                    rtmpPort = staticMediaKitProperties.getRtmpPort();
                }
                if (staticMediaKitProperties.getRecord() != null 
                    && staticMediaKitProperties.getRecord().getApp() != null) {
                    app = staticMediaKitProperties.getRecord().getApp();
                }
            }
            
            // RTMP 地址格式：rtmp://mediakit_host:rtmp_port/app/stream
            String rtmpUrl = String.format("rtmp://%s:%d/%s/%s",
                    host,
                    rtmpPort,
                    app,
                    streamId);
            
            log.debug("构建RTMP地址: host={}, port={}, app={}, streamId={}, url={}", 
                host, rtmpPort, app, streamId, rtmpUrl);
            
            return rtmpUrl;
        }
        return null;
    }
    
    /**
     * 根据摄像头信息生成 HTTP 流地址
     * 
     * @param camera 摄像头对象
     * @return HTTP 流地址，如果配置不完整返回 null
     */
    public static String buildHttpUrl(HwCamera camera) {
        if (camera == null) {
            return null;
        }
        
        if (StrUtil.isAllNotBlank(camera.getCameraIp()) && camera.getCameraPort() != null) {
            return String.format("http://%s:%d/stream", 
                    camera.getCameraIp(), 
                    camera.getCameraPort());
        }
        return null;
    }
    
    /**
     * 转换 WebRTC 地址为 HTTP-FLV 地址
     * 
     * @param webrtcUrl WebRTC 播放地址
     * @return HTTP-FLV 地址，转换失败返回 null
     */
    public static String convertWebRtcToFlv(String webrtcUrl) {
        if (StrUtil.isBlank(webrtcUrl)) {
            return null;
        }
        
        // 如果已经是标准流格式，直接返回
        String lowerUrl = webrtcUrl.toLowerCase();
        if (lowerUrl.startsWith("rtsp://") || 
            lowerUrl.startsWith("rtmp://") || 
            lowerUrl.endsWith(".flv") ||
            lowerUrl.endsWith(".m3u8")) {
            return webrtcUrl;
        }
        
        // 解析 WebRTC URL，提取 app 和 stream 参数
        try {
            java.net.URL url = new java.net.URL(webrtcUrl);
            String host = url.getHost();
            int port = url.getPort() > 0 ? url.getPort() : 80;
            String query = url.getQuery();
            
            if (StrUtil.isBlank(query)) {
                return null;
            }
            
            // 解析查询参数
            String app = null;
            String stream = null;
            for (String param : query.split("&")) {
                String[] kv = param.split("=");
                if (kv.length == 2) {
                    if ("app".equals(kv[0])) {
                        app = kv[1];
                    } else if ("stream".equals(kv[0])) {
                        stream = kv[1];
                    }
                }
            }
            
            if (StrUtil.isBlank(app) || StrUtil.isBlank(stream)) {
                log.warn("无法从 WebRTC URL 中提取 app 或 stream 参数: {}", webrtcUrl);
                return null;
            }
            
            // 构建 HTTP-FLV 地址
            String flvUrl = String.format("http://%s:%d/%s/%s.live.flv", host, port, app, stream);
            log.debug("转换流地址: {} -> {}", webrtcUrl, flvUrl);
            return flvUrl;
            
        } catch (Exception e) {
            log.error("转换流地址失败: {}", webrtcUrl, e);
            return null;
        }
    }
}

